/*
	身份证信息识别
	apikey:GhMmCkAeml9OGsq9x2wThnuo
	secretkey:nVgh1xBzxAtIeaStrN328SubOypGfL1Q
	id:41302303
*/

import image from "../uni_modules/uview-ui/libs/config/props/image";

//获取AccessToken
function getAccessToken(){
	return new Promise((resolve,reject)=>{
		uni.request({
			url:'https://aip.baidubce.com/oauth/2.0/token?client_id=GhMmCkAeml9OGsq9x2wThnuo&client_secret=nVgh1xBzxAtIeaStrN328SubOypGfL1Q&grant_type=client_credentials',
			method:'POST',
			header:{
				'Content-Type': 'application/json',
				'Accept': 'application/json'
			},
			success(res) {
				return resolve(res.data.access_token)
			},
			fail(err) {
				return reject(null)
			}
		})
	})
}

//获取身份证信息
async function getIdCardInfo(url,callback){
	let token = await getAccessToken();
	getBase64Image(url,image=>{
		uni.request({
			url:'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + token,
			method:'POST',
			header:{
				'Content-Type': 'application/x-www-form-urlencoded',
				'Accept': 'application/json'
			},
			data:{
				'id_card_side': 'back',
				'image':image,
				'detect_risk': 'false',
				'detect_quality': 'false',
				'detect_photo': 'false',
				'detect_card': 'false',
				'detect_direction': 'false'
			},
			success(res) {
				callback && callback(res)
			},
			fail(err) {
				console.log(err);
			}
		})
	});
}

//图片转base64格式
const getBase64Image = (src,callback) => {
    // #ifdef MP-WEIXIN
	uni.getFileSystemManager().readFile({
		filePath: src, 
		encoding: 'base64', 
		success: res => { 
		  let base64 = 'data:image/jpeg;base64,' + res.data
		  callback && callback(base64)
		},
		fail: (e) => {
		  console.log("图片转换失败");
		}
	})
	// #endif
	// #ifdef APP-PLUS
	plus.io.resolveLocalFileSystemURL(src, (entry) => {
	    entry.file((file) => {
	      let fileReader = new plus.io.FileReader();
	      if (file.size > 450 * 1024) {
	        return uni.showToast({
	          title: '图片大小不能超过450k',
	          icon: 'none'
	        })
	      }
	      fileReader.onloadend = (e) => {
	        callback && callback(e.target.result)
	      };
	      fileReader.readAsDataURL(file);
	    })
	})
	// #endif
}

export default getIdCardInfo
